/*
 * 
 * 
 * 
 */
package com.cms.controller.admin;

import com.cms.config.SysConfig;
import com.cms.constant.Constant;
import com.cms.domain.Config;
import com.cms.service.ConfigService;
import com.cms.utils.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Controller - 文件
 * 
 * 
 * 
 */
@Slf4j
@Controller("adminFileController")
@RequestMapping("/admin/file")
public class FileController extends BaseController {

    @Autowired
    private ConfigService configService;


    /**
     * 上传
     */
    @ResponseBody
    @RequestMapping("/upload")
    public Map<String, Object> upload(MultipartFile file) throws IOException {
        Map<String, Object> data = new HashMap<String, Object>();
        if (file.isEmpty()) {
            data.put("message", "操作错误");
            data.put("state", "ERROR");
            return data;
        }
        String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
        String newFileBaseName = UUID.randomUUID().toString();
        String newFileName = newFileBaseName+"."+suffix;
//        String url = "/"+ CommonConstant.UPLOAD_PATH+"/"+newFileName;
//        File newFile = new File(PathUtils.getWebRootPath()+url);
//        file.transferTo(newFile);
        String uploadDir = SysConfig.getImagePath();
        File newFile = new File(uploadDir + File.separator + newFileName);
        String absPath = newFile.getAbsolutePath();
        if (!newFile.exists())
        {
            if (!newFile.getParentFile().exists())
            {
                newFile.getParentFile().mkdirs();
            }
        }
        file.transferTo(Paths.get(absPath));
        String url = getPathFileName(uploadDir, newFileName);

        String [] imageSuffixs = new String[]{"jpg","png","jpeg"};
        Config config = configService.getConfig();
        if(config.getIsWatermarkEnabled() && ArrayUtils.contains(imageSuffixs, suffix.toLowerCase())){
            String watermarkImage = config.getWatermarkImage();
            String watermarkPosition = config.getWatermarkPosition();
//            File watermarkImageFile = new File(PathUtils.getWebRootPath()+watermarkImage);
//            String sourceFileName = newFileBaseName+"_source."+suffix;
//            File sourceFile = new File(PathUtils.getWebRootPath()+"/"+ CommonConstant.UPLOAD_PATH+"/"+sourceFileName);
            log.info("watermarkImage路径:{}", watermarkImage);
            File watermarkImageFile = getWatermarkImageFile(watermarkImage);
            File sourceFile = new File(uploadDir + File.separator +"source_" + newFileName);
            newFile.renameTo(sourceFile);
            ImageUtils.addWatermark(sourceFile, newFile, watermarkImageFile, watermarkPosition);
            FileUtils.deleteQuietly(sourceFile);
        }
        data.put("message", "成功");
        data.put("state", "SUCCESS");
        data.put("url", url);
        data.put("name",FilenameUtils.getBaseName(url));
        return data;
    }

    public static final String getPathFileName(String uploadDir, String fileName) throws IOException
    {
        int dirLastIndex = SysConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        return Constant.RESOURCE_PREFIX + "/" + currentDir + fileName;
    }

    public Resource getWatermarkImageResource(String imagePath) {
        Resource resource = new ClassPathResource(imagePath);
        if (!resource.exists()) {
            // Try to get the resource from the root of the classpath (for JAR execution)
            resource = new ClassPathResource(imagePath);
        }
        if (resource.exists()) {
            return resource;
        } else {
            throw new IllegalStateException("Watermark image not found.");
        }
    }

    public File getWatermarkImageFile(String imagePath) throws IOException {
        Resource resource = getWatermarkImageResource(imagePath);
        InputStream inputStream = resource.getInputStream();
        File tempFile = File.createTempFile("watermark", ".png");
        tempFile.deleteOnExit();
        Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return tempFile;
    }

}